let { ipcMain, BrowserWindow } = require("electron")
let fs = require("fs")
let path = require("path")
// let win = BrowserWindow.getFocusedWindow()
let win = BrowserWindow.fromId(global.mainId)

let musicIndex = 1 // 本地歌曲的序号


// 最大化
ipcMain.on("maximize", (event) => {
    if (win.isMaximized()) {
        win.restore()
    } else {
        win.maximize()
    }
})
// 最小化
ipcMain.on("minimize", (event) => {
    win.minimize()
})

// 隐藏
ipcMain.on("hide", () => {
    win.hide()
})

// 显示主界面，由系统托盘菜单触发(Tray.vue)
ipcMain.on("showWindow", () => {
    win.show()
})

// 退出
ipcMain.on("winClose", () => {
    win.close()
})

// 添加本地音乐，遍历文件夹
ipcMain.on("scanFolder", (e, directory) => {
    let res = []
    musicIndex = 1
    directory.forEach(item => {
        res.push(...scanFiles(item))
    })
    win.webContents.send('addMusic', res)
})

//提取一个目录文件夹里指定类型（如：同一后缀名）的文件
function scanFiles(dir) {
    var results = []
    var list = fs.readdirSync(dir)
    list.forEach(function (file) {
        file = dir + '\\' + file
        var stat = fs.statSync(file)
        if (stat && stat.isDirectory()) {
            results = results.concat(scanFiles(file))
        } else {
            // 过滤后缀名（可按你需求进行新增）
            if (path.extname(file) === '.mp3' || path.extname(file) === '.wav') {
                let fileName = path.basename(file).split(".")
                let name = fileName[0]
                results.push({
                    index: musicIndex,
                    name,
                    path: path.resolve(__dirname, file)
                })
                musicIndex++
            }
        }
    })
    return results
}